package com.pzsh.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pzsh.aliyun.api.gateway.demo.BankAuth;
import com.pzsh.aliyun.api.gateway.demo.util.HttpUtils;
import com.pzsh.constant.ConstantInterface;
import com.pzsh.constant.EOLINKERConstants;
import com.pzsh.constant.ThreadPoolsConstants;
import com.pzsh.entity.*;
import com.pzsh.entity.vo.*;
import com.pzsh.enums.ErrorCodeEnum;
import com.pzsh.exception.ApiException;
import com.pzsh.jwt.ITokenManager;
import com.pzsh.mapper.*;
import com.pzsh.redis.IRedisService;
import com.pzsh.service.IUserService;
import com.pzsh.sms.aliyun.SendSms;
import com.pzsh.util.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMethod;
import tk.mybatis.mapper.entity.Example;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.pzsh.constant.StaticVal.FACK_ADD;
import static com.pzsh.constant.StaticVal.isWindows;

/**
 * @Description:
 * @Param:
 * @return:
 * @Author: GXL
 * @Date: 2019/12/05
 */
@Slf4j
@Service
@Transactional(propagation = Propagation.SUPPORTS)
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WhiteUserMapper whiteUserMapper;

    @Autowired
    private SpecialMapper specialMapper;

    @Autowired
    private IRedisService redisService;

    @Autowired
    private ITokenManager tokenManager;

    @Autowired
    private ReceivAddressMapper receivAddressMapper;
    @Autowired
    private FriendsMapper friendsMapper;

    @Autowired
    private GradeConditionMapper gradeConditionMapper;
    @Autowired
    private CensusMapper censusMapper;

    @Autowired
    private UserPackMapper userPackMapper;

    @Autowired
    private UserProfitMapper userProfitMapper;

    @Autowired
    private UserProfitTodayMapper userProfitTodayMapper;
    @Autowired
    private SpendMoneyMapper spendMoneyMapper;
    @Autowired
    private GradeMapper gradeMapper;
    @Autowired
    private TransactionssMapper transactionssMapper;

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void sendVerificationCodeForRegister(String mobile) {

        String vcode = String.valueOf((int)(Math.random()*(9999-1000+1)+1000));

        redisService.setString(ConstantInterface.VERIFICATION_CODE_FOR_REGISTER + mobile, vcode, 10, TimeUnit.MINUTES);
        SendSms.send(vcode,mobile);

//        String res = SendSms.send(vcode,mobile);
//        JSONObject jsonres = JSONObject.parseObject(res);
//        if (!"OK".equals(jsonres.getString("Code"))){
//            throw new ApiException(ErrorCodeEnum.PARAM_200012.code(),ErrorCodeEnum.PARAM_200012.msg());
//        }
//        redisService.setString(ConstantInterface.VERIFICATION_CODE_FOR_REGISTER + mobile, vcode, 1, TimeUnit.MINUTES);

    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void sendVerificationCodeForChangePassword(String account) {
        String vcode = String.valueOf((int)(Math.random()*(9999-1000+1)+1000));

        UserEntity entity = new UserEntity();
        entity.setAccount(account);//使用用户名查找
        entity = userMapper.selectOne(entity);
        String mobile = entity.getMobile();

        redisService.setString(ConstantInterface.VERIFICATION_CODE_FOR_CHANGE_PASSWORD + mobile, vcode, 10, TimeUnit.MINUTES);
        SendSms.send(vcode,mobile);

//        String res = SendSms.send(vcode, mobile);
//        JSONObject jsonres = JSONObject.parseObject(res);
//        if (!"OK".equals(jsonres.getString("Code"))){
//            throw new ApiException(ErrorCodeEnum.PARAM_200012.code(),ErrorCodeEnum.PARAM_200012.msg());
//        }
//        redisService.setString(ConstantInterface.VERIFICATION_CODE_FOR_CHANGE_PASSWORD + mobile, vcode, 1, TimeUnit.MINUTES);
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void checkVerificationCodeOfChangePassword(String account, String code) {

        UserEntity entity = new UserEntity();
        entity.setAccount(account);
        entity = userMapper.selectOne(entity);
        String mobile = entity.getMobile();

        String vcode = redisService.getString(ConstantInterface.VERIFICATION_CODE_FOR_CHANGE_PASSWORD + mobile);
        if (!code.equals(vcode)){
            throw new ApiException(ErrorCodeEnum.TK1015.code(),ErrorCodeEnum.TK1015.msg());
        }

        redisService.deleteString(ConstantInterface.VERIFICATION_CODE_FOR_CHANGE_PASSWORD + mobile);
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public UserVo userLogin(String account, String password) {

//        if (redisService.hasKey(ConstantInterface.USER_LOGIN + account)){
//            redisService.deleteString(ConstantInterface.USER_LOGIN + account);
////            throw  new ApiException(ErrorCodeEnum.TK1018.code(),ErrorCodeEnum.TK1018.msg());
//        }

        UserEntity entity = new UserEntity();
        entity.setAccount(account);//使用用户名查找
        entity = userMapper.selectOne(entity);
        if (entity == null){//使用用户名查找时，用户不存在
            entity = new UserEntity();
            entity.setMobile(account);//使用手机号查找
            entity = userMapper.selectOne(entity);
            if (entity == null) {//使用手机号查找时，用户不存在
                throw  new ApiException(ErrorCodeEnum.SW50.code(),ErrorCodeEnum.SW50.msg());
            }

            //此处
            List<UserEntity> ul = userMapper.select(entity);
            if (ul.size() > 1 && "13080567678".equals(ul.get(0).getMobile())){
                entity = ul.get(0);
            }
        }

        password = MD5Util.MD5Encode(password,"utf-8");
        if (!entity.getPassword().equals(password)){
            throw  new ApiException(ErrorCodeEnum.SW30.code(),ErrorCodeEnum.SW30.msg());
        }

        if (entity.getBlack().equals(1)){//已被拉黑
            throw new ApiException(ErrorCodeEnum.TK1012.code(),ErrorCodeEnum.TK1012.msg());
        }

        WhiteUserEntity whiteUserEntity = new WhiteUserEntity();
        whiteUserEntity.setUserId(entity.getUserId());
        whiteUserEntity = whiteUserMapper.selectOne(whiteUserEntity);
        if (whiteUserEntity==null){//系统没有将用户添加为白名单，则正常判断下去
            Long now = new Date().getTime();
            Long registerTime = entity.getCreateDate().getTime();
            Long gate = now - registerTime;
            Long hours24 = 24 * 60 * 60 * 1000L;
            if (gate > hours24 && entity.getGrade().equals(-1)){//超过二十四小时未升级vip则拉黑
                final UserEntity black = entity;
                ThreadPoolsConstants.blackThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        black.setBlack(1);//标记为拉黑
                        black.setModifyDate(new Timestamp(new Date().getTime()));
                        userMapper.updateByPrimaryKey(black);
                    }
                });
                throw new ApiException(ErrorCodeEnum.TK1012.code(),ErrorCodeEnum.TK1012.msg());
            }
        }


        //允许登录
        String loginKey = ConstantInterface.TOKEN_REDIS_KEY + entity.getAccount();
        if (redisService.hasKey(loginKey)){
//            String oldToken = redisService.getString(loginKey);
//            redisService.deleteString(oldToken);
            redisService.deleteString(loginKey);
        }

        //生成推广二维码
        final String fromUser = String.valueOf(entity.getAccount());
        final UserEntity updateUser = entity;
        if (StringUtils.isBlank(entity.getQrCode())){
            ThreadPoolsConstants.qrThreadPool.execute(new Runnable(){
                @Override
                public void run() {
                    if(isWindows){
                        String visitPath = "myimg" + File.separator + "qr_code";
                        String qr_mkdir = File.listRoots()[0].getAbsolutePath() +  visitPath;
                        File file = new File(qr_mkdir);
                        if (!file.exists()){
                            file.mkdirs();
                        }
                        try {
                            Long ti = new Date().getTime();
                            String filename = "qr" + ti + "_" + fromUser;
                            String content = FACK_ADD + "/codeLink/index.html?pid=" + fromUser;
                            String picPath = QRcodeImageUtil.buildQuickMark(content, qr_mkdir, filename);
                            String filePath = FACK_ADD + "myimg/qr_code/" + filename + ".png";
                            updateUser.setQrCode(filePath);
                            userMapper.updateByPrimaryKey(updateUser);
                            log.info("已生成用户推广二维码，存放路径：{}", picPath);
                        } catch (Exception e) {
                            log.error("生成用户推广二维码出现异常：{}", e.getMessage());
                        }
                    }else{
                        String visitPath = "/myimg" + File.separator + "qr_code";
                        File file = new File(visitPath);
                        if (!file.exists()){
                            file.mkdirs();
                        }
                        try {
                            Long ti = new Date().getTime();
                            String filename = "qr_" + ti + "_" + fromUser;
                            String content = FACK_ADD + "/codeLink/index.html?pid=" + fromUser;
                            String picPath = QRcodeImageUtil.buildQuickMark(content, visitPath, filename);
                            String filePath = FACK_ADD + "myimg/qr_code/" + filename + ".png";
                            updateUser.setQrCode(filePath);
                            userMapper.updateByPrimaryKey(updateUser);
                            log.info("已生成用户推广二维码，存放路径：{}", picPath);
                        } catch (Exception e) {
                            log.error("生成用户推广二维码出现异常：{}", e.getMessage());
                        }
                    }
                }
            });
        }

        Map<String, Object> clamis = new HashMap<>();
        clamis.put("account", entity.getAccount());
        String token = tokenManager.createToken(entity.getUserId(), entity.getAccount(), clamis).getToken();
        if(StringUtils.isNullStr(token)){
            throw new ApiException(ErrorCodeEnum.TK1003);
        }

        //存储到redis并设置过期时间
        redisService.setString(loginKey, token, ConstantInterface.TOKEN_EXPIRES_HOUR, TimeUnit.SECONDS);
        //缓存记录已登录
//        redisService.setString(token, entity.getAccount(),2,TimeUnit.DAYS);
        UserVo vo = new UserVo();
        vo.setToken(token);
        vo.setAccount(entity.getAccount());
        vo.setBlack(entity.getBlack());
        vo.setHead(entity.getHead());
        vo.setMobile(entity.getMobile());
        vo.setStatus(entity.getStatus());
        vo.setGrade(entity.getGrade());
        return vo;

    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void registry(String account, String mobile, String code, String pass, String visitAccount){
        String vcode = redisService.getString(ConstantInterface.VERIFICATION_CODE_FOR_REGISTER + mobile);
        if (!code.equals(vcode)){
            throw new ApiException(ErrorCodeEnum.TK1015.code(),ErrorCodeEnum.TK1015.msg());
        }
        UserEntity entity = new UserEntity();
        entity.setAccount(account);
        entity = userMapper.selectOne(entity);
        if (entity != null){
            throw new ApiException(ErrorCodeEnum.SW51.code(),ErrorCodeEnum.SW51.msg());
        }

        UserEntity visitAcc = new UserEntity();
        visitAcc.setAccount(visitAccount);
        visitAcc = userMapper.selectOne(visitAcc);
        if (visitAcc == null){
            throw new ApiException(ErrorCodeEnum.PARAM_200017.code(),ErrorCodeEnum.PARAM_200017.msg());
        }
        if (visitAcc.getGrade()==-1){
            throw new ApiException(ErrorCodeEnum.PARAM_200025.code(),ErrorCodeEnum.PARAM_200025.msg());
        }

        UserEntity entitymm = new UserEntity();
        entitymm.setMobile(mobile);
        entitymm = userMapper.selectOne(entitymm);
        if (entitymm != null){
            throw new ApiException(ErrorCodeEnum.SW53.code(),ErrorCodeEnum.SW53.msg());
        }

        pass = MD5Util.MD5Encode(pass,"utf-8");

        //用户注册
        entity = new UserEntity();
        entity.setAccount(account);
        entity.setPassword(pass);
        entity.setMobile(mobile);
        entity.setVisitAccount(visitAccount);
        entity.setGrade(-1);
        entity.setBlack(0);
        entity.setStatus(0);
        entity.setHead("http://api.shoppzsh.com/myimg/defaultImg.png");
        entity.setIdCard("--");
        entity.setRealName("--");
        entity.setBankCard("--");
        entity.setCreateDate(new Timestamp(new Date().getTime()));
        entity.setModifyDate(new Timestamp(new Date().getTime()));
        userMapper.insert(entity);

        log.info("添加用户后的userId = {}", entity.getUserId()==null?"null":entity.getUserId());
        Integer superid = 0;

        //保存推荐人的好友
        UserEntity visitor = new UserEntity();
        visitor.setAccount(visitAccount);
        visitor = userMapper.selectOne(visitor);
        superid = visitor.getUserId();
        FriendsEntity friendsEntity = new FriendsEntity();
        friendsEntity.setFriends_id(entity.getUserId());
        friendsEntity.setFriendsName(entity.getAccount());
        friendsEntity.setMobile(entity.getMobile());
        friendsEntity.setUserId(visitor.getUserId());
        friendsEntity.setUserName(visitor.getAccount());
        friendsMapper.insert(friendsEntity);

        //初始化用户消费累计记录
        UserSpendEntity userSpendEntity = new UserSpendEntity();
        userSpendEntity.setSpendMoney(0);
        userSpendEntity.setSpendMoneyGoods(0);
        userSpendEntity.setSpendMoneyGrade(0);
        userSpendEntity.setUserId(entity.getUserId());
        spendMoneyMapper.insert(userSpendEntity);

        //初始化用户钱包，0
        UserPackEntity userPackEntity = new UserPackEntity();
        userPackEntity.setUserId(entity.getUserId());
        userPackEntity.setFreeIntegral(0);
        userPackEntity.setRewardIntegral(0);
        userPackEntity.setEUSDT(0);
        userPackEntity.setPZSH(0);
        userPackEntity.setRdIntegral(0);
        userPackEntity.setUnuseIntegral(0);
        userPackMapper.insert(userPackEntity);

        //初始化注册用户的团队成员
        GradeConditionEntity gradeConditionEntity = new GradeConditionEntity();
        gradeConditionEntity.setFriends(0);
        gradeConditionEntity.setReConsumption(0);
        gradeConditionEntity.setTeam(0);
        gradeConditionEntity.setUserId(entity.getUserId());
        gradeConditionEntity.setUserName(entity.getAccount());
        gradeConditionEntity.setSuperName(visitAccount);
        gradeConditionEntity.setSuperId(superid);
        gradeConditionMapper.insert(gradeConditionEntity);

        //**累计用户总数
        CensusEntity censusEntity = censusMapper.selectAll().get(0);
        censusEntity.setCountUser(censusEntity.getCountUser()+1);
        censusMapper.updateByPrimaryKey(censusEntity);

        //初始化用户总收益记录
        UserProfitEntity userProfitEntity = new UserProfitEntity();
        userProfitEntity.setAccount(entity.getAccount());
        userProfitEntity.setUserId(entity.getUserId());
        userProfitEntity.setPsProfit(0);
        userProfitEntity.setPzshProfit(0);
        userProfitEntity.setPzshReward(0);
        userProfitMapper.insert(userProfitEntity);

        //初始化用户今日收益记录
        Long nowTime = new Date().getTime();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Long rewardDateForFind = Long.valueOf(dateFormat.format(nowTime));
        UserProfitTodayEntity userProfitTodayEntity = new UserProfitTodayEntity();
        userProfitTodayEntity.setToday(String.valueOf(rewardDateForFind));
        userProfitTodayEntity.setUserId(entity.getUserId());
        userProfitTodayEntity = userProfitTodayMapper.selectOne(userProfitTodayEntity);
        if (userProfitTodayEntity == null){
            userProfitTodayEntity = new UserProfitTodayEntity();
            userProfitTodayEntity.setAccount(entity.getAccount());
            userProfitTodayEntity.setUserId(entity.getUserId());
            userProfitTodayEntity.setPsProfit(0);
            userProfitTodayEntity.setPzshProfit(0);
            userProfitTodayEntity.setPzshReward(0);
            userProfitTodayEntity.setToday(String.valueOf(rewardDateForFind));
            userProfitTodayEntity.setCreateDate(new Timestamp(new Date().getTime()));
            userProfitTodayEntity.setModifyDate(new Timestamp(new Date().getTime()));
            userProfitTodayMapper.insert(userProfitTodayEntity);
        }

        //初始化明日的收益记录
        Long nowTime2 = new Date().getTime() + 24 * 60 * 60 * 1000L;
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyyMMdd");
        Long rewardDateForFind2 = Long.valueOf(dateFormat2.format(nowTime2));
        UserProfitTodayEntity userProfitTodayEntity2 = new UserProfitTodayEntity();
        userProfitTodayEntity2.setToday(String.valueOf(rewardDateForFind2));
        userProfitTodayEntity2.setUserId(entity.getUserId());
        userProfitTodayEntity2 = userProfitTodayMapper.selectOne(userProfitTodayEntity2);
        if (userProfitTodayEntity2 == null){
            userProfitTodayEntity2 = new UserProfitTodayEntity();
            userProfitTodayEntity2.setAccount(entity.getAccount());
            userProfitTodayEntity2.setUserId(entity.getUserId());
            userProfitTodayEntity2.setPsProfit(0);
            userProfitTodayEntity2.setPzshProfit(0);
            userProfitTodayEntity2.setPzshReward(0);
            userProfitTodayEntity2.setToday(String.valueOf(rewardDateForFind2));
            userProfitTodayEntity2.setCreateDate(new Timestamp(new Date().getTime()));
            userProfitTodayEntity2.setModifyDate(new Timestamp(new Date().getTime()));
            userProfitTodayMapper.insert(userProfitTodayEntity2);
        }

        //请求RD积分系统接口--创建用户
        Map<String, String> headers = new HashMap<String, String>();
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("username", entity.getAccount());
        bodys.put("name", "");
        bodys.put("nickname", "");
        bodys.put("p_username", entity.getVisitAccount());
        bodys.put("mobile", entity.getMobile());
        try {
            log.info("DOMAIN_URL: " + EOLINKERConstants.DOMAIN_URL);
            HttpResponse response = HttpUtils.doPost(EOLINKERConstants.DOMAIN_URL, EOLINKERConstants.USER_ADD, RequestMethod.POST.name(),headers,querys,bodys);
            String str = EntityUtils.toString(response.getEntity());
            log.info("RD系统返回-创建用户：{}", str);
            JSONObject jsonObject = JSONObject.parseObject(str);//.getJSONObject("data")
            Integer status = jsonObject.getInteger("status");
            if (!status.equals(0)){
                throw new ApiException(ErrorCodeEnum.PARAM_200014.code(),String.format(ErrorCodeEnum.PARAM_200014.msg(),"创建用户"));
            }
        } catch (Exception e) {
            throw new ApiException(ErrorCodeEnum.PARAM_200014.code(),String.format(ErrorCodeEnum.PARAM_200014.msg(),"创建用户"));
        }

        redisService.deleteString(ConstantInterface.VERIFICATION_CODE_FOR_REGISTER + mobile);
    }


    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public UserVo getUser(String account) {
        UserEntity userEntity = new UserEntity();
        userEntity.setAccount(account);
        userEntity = userMapper.selectOne(userEntity);

        UserVo vo = new UserVo();
        vo.setGrade(userEntity.getGrade());
        vo.setMobile(userEntity.getMobile());
        vo.setHead(userEntity.getHead());
        vo.setAccount(userEntity.getAccount());
        vo.setBlack(userEntity.getBlack());
        vo.setStatus(userEntity.getStatus());
        vo.setRealName(userEntity.getRealName());
        vo.setUserId(userEntity.getUserId());
        vo.setBankCard(userEntity.getBankCard());
        vo.setIdCard(userEntity.getIdCard());
        vo.setPayPwd(userEntity.getPayPwd());
        vo.setQrCode(userEntity.getQrCode());
        vo.setVisitAccount(userEntity.getVisitAccount());
        vo.setCreateDate(userEntity.getCreateDate());
        vo.setModifyDate(userEntity.getModifyDate());


        GradeEntity gradeEntity = new GradeEntity();
        gradeEntity.setFromGrade(userEntity.getGrade());
        gradeEntity = gradeMapper.selectOne(gradeEntity);
        vo.setFinishRecommed(gradeEntity.getRecommend());
        vo.setFinishTeam(gradeEntity.getTeam());

        //判断团队人数--数据来源RD系统
        Integer group = 0 ;
        //判断直推人数是否符合购买条件
        Integer child = 0 ;
        try {
            Map<String, String> headers = new HashMap<String, String>();
            Map<String, String> querys = new HashMap<String, String>();
            Map<String, String> bodys = new HashMap<String, String>();
            bodys.put("username", account);
            HttpResponse response = HttpUtils.doPost(EOLINKERConstants.DOMAIN_URL,EOLINKERConstants.USER_NUMBER, RequestMethod.POST.name(),headers,querys,bodys);
            String str = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(str);
//            log.info("RD系统返回-我的会员人数统计：{}",jsonObject.toJSONString());
            Integer status = jsonObject.getInteger("status");
            if (!status.equals(0)){
                throw new ApiException(ErrorCodeEnum.PARAM_200014.code(),String.format(ErrorCodeEnum.PARAM_200014.msg(),"我的会员人数统计"));
            }
            group = jsonObject.getJSONObject("data").getInteger("group");
            child = jsonObject.getJSONObject("data").getInteger("child");
            vo.setRecommed(child);
            vo.setTeam(group);
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            throw new ApiException(ErrorCodeEnum.PARAM_200014.code(),String.format(ErrorCodeEnum.PARAM_200014.msg(),"我的会员人数统计"));
        }
        return vo;
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void updatePassWord(String account, String password) {

        password = MD5Util.MD5Encode(password,"utf-8");

        UserEntity oo = new UserEntity();
        oo.setAccount(account);
        UserEntity entity = userMapper.selectOne(oo);
        entity.setPassword(password);
        userMapper.updateByPrimaryKey(entity);
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void updatePassWord2(String account, String password, String vcode) {

        password = MD5Util.MD5Encode(password,"utf-8");

        UserEntity oo = new UserEntity();
        oo.setAccount(account);
        UserEntity entity = userMapper.selectOne(oo);

        if(!vcode.equals(redisService.getString(ConstantInterface.VERIFICATION_CODE_FOR_CHANGE_PASSWORD + entity.getMobile()))){
            throw new ApiException(ErrorCodeEnum.TK1015.code(), ErrorCodeEnum.TK1015.msg());
        }
        entity.setPassword(password);
        userMapper.updateByPrimaryKey(entity);
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void userAuth(String account, String realName, String idCard, String bankCard, String bankMobile) {

        UserEntity oo = new UserEntity();
        oo.setAccount(account);
        UserEntity entity = userMapper.selectOne(oo);

        if (entity.getStatus().equals(1)){
            throw new ApiException(ErrorCodeEnum.TK1017.code(),ErrorCodeEnum.TK1017.msg());
        }
        if (entity.getBlack().equals(1)){
            throw new ApiException(ErrorCodeEnum.TK1012.code(),ErrorCodeEnum.TK1012.msg());
        }

        UserEntity idcardUser = new UserEntity();
        idcardUser.setIdCard(idCard);
        idcardUser = userMapper.selectOne(idcardUser);
        if (idcardUser!=null){
            throw new ApiException(ErrorCodeEnum.TK1020.code(),ErrorCodeEnum.TK1020.msg());
        }

        String authRes = BankAuth.check(bankCard,idCard,realName,bankMobile);
        JSONObject json = JSONObject.parseObject(authRes);
        String status = json.getString("status");
        if (StringUtils.isNullStr(status)){
            throw new ApiException(ErrorCodeEnum.PARAM_200022.code(),ErrorCodeEnum.PARAM_200022.msg());
        }
        if (!"OK".equals(status)){
            if ("INVALID_ARGUMENT".equals(status)){
                throw new ApiException(ErrorCodeEnum.PARAM_200008.code(),ErrorCodeEnum.PARAM_200008.msg());
            }
            if ("RATE_LIMIT_EXCEEDED".equals(status)){
                throw new ApiException(ErrorCodeEnum.PARAM_200009.code(),ErrorCodeEnum.PARAM_200009.msg());
            }
            if ("DATA_SERVER_ERROR".equals(status)){
                throw new ApiException(ErrorCodeEnum.PARAM_200010.code(),ErrorCodeEnum.PARAM_200010.msg());
            }
            if ("TRADE_LIMIT".equals(status)){
                throw new ApiException(ErrorCodeEnum.PARAM_200024.code(),ErrorCodeEnum.PARAM_200024.msg());
            }
            throw new ApiException(ErrorCodeEnum.PARAM_200011.code(), status);
        }else{
            if (json.getInteger("result")==2){
                throw new ApiException(ErrorCodeEnum.AUTH_2.code(),ErrorCodeEnum.AUTH_2.msg());
            }
            if (json.getInteger("result")==30){
                throw new ApiException(ErrorCodeEnum.AUTH_30.code(),ErrorCodeEnum.AUTH_30.msg());
            }
            if (json.getInteger("result")==31){
                throw new ApiException(ErrorCodeEnum.AUTH_31.code(),ErrorCodeEnum.AUTH_31.msg());
            }
            if (json.getInteger("result")==32){
                throw new ApiException(ErrorCodeEnum.AUTH_32.code(),ErrorCodeEnum.AUTH_32.msg());
            }
            if (json.getInteger("result")==33){
                throw new ApiException(ErrorCodeEnum.AUTH_33.code(),ErrorCodeEnum.AUTH_33.msg());
            }
            if (json.getInteger("result")==34){
                throw new ApiException(ErrorCodeEnum.AUTH_34.code(),ErrorCodeEnum.AUTH_34.msg());
            }
            if (json.getInteger("result")==35){
                throw new ApiException(ErrorCodeEnum.AUTH_35.code(),ErrorCodeEnum.AUTH_35.msg());
            }
            if (json.getInteger("result")==36){
                throw new ApiException(ErrorCodeEnum.AUTH_36.code(),ErrorCodeEnum.AUTH_36.msg());
            }
            if (json.getInteger("result")==37){
                throw new ApiException(ErrorCodeEnum.AUTH_37.code(),ErrorCodeEnum.AUTH_37.msg());
            }
            if (json.getInteger("result")==38){
                throw new ApiException(ErrorCodeEnum.AUTH_38.code(),ErrorCodeEnum.AUTH_38.msg());
            }
            if (json.getInteger("result")==39){
                throw new ApiException(ErrorCodeEnum.AUTH_39.code(),ErrorCodeEnum.AUTH_39.msg());
            }
            if (json.getInteger("result")==40){
                throw new ApiException(ErrorCodeEnum.AUTH_40.code(),ErrorCodeEnum.AUTH_40.msg());
            }
        }

        entity.setModifyDate(new Timestamp(new Date().getTime()));
        entity.setRealName(realName);
        entity.setIdCard(idCard);
        entity.setBankCard(bankCard);
        entity.setBankMobile(bankMobile);
        entity.setStatus(1);
        userMapper.updateByPrimaryKey(entity);
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void loginOut(String account) {
        String loginKey = ConstantInterface.TOKEN_REDIS_KEY + account;
        if (redisService.hasKey(loginKey)){
//            String oldToken = redisService.getString(loginKey);
//            redisService.deleteString(oldToken);
            redisService.deleteString(loginKey);
        }
//        if (redisService.hasKey(ConstantInterface.USER_LOGIN + account)){
//            redisService.deleteString(ConstantInterface.USER_LOGIN + account);
//        }
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public ReceivAddressVo getAddress(String account) {
        UserEntity oo = new UserEntity();
        oo.setAccount(account);
        oo = userMapper.selectOne(oo);

        ReceivAddressEntity receivAddressEntity = new ReceivAddressEntity();
        receivAddressEntity.setUserId(oo.getUserId());
        receivAddressEntity = receivAddressMapper.selectOne(receivAddressEntity);

        //如果地址信息为空
        if (Objects.isNull(receivAddressEntity)){
            return null;
        }

        ReceivAddressVo  vo = new ReceivAddressVo();
        vo.setAddress(receivAddressEntity.getAddress());
        vo.setCityProv(receivAddressEntity.getCityProv());
        vo.setConsignee(receivAddressEntity.getConsignee());
        vo.setConsigneeMobile(receivAddressEntity.getConsigneeMobile());

        return vo;
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void sendVerificationCodeForChangeMobile(String mobile, String account) {
        String vcode = String.valueOf((int)(Math.random()*(9999-1000+1)+1000));

        redisService.setString(ConstantInterface.VERIFICATION_CODE_FOR_CHANGE_MOBILE + mobile, vcode, 1, TimeUnit.MINUTES);
        SendSms.send(vcode,mobile);

//        String res = SendSms.send(vcode,mobile);
//        JSONObject jsonres = JSONObject.parseObject(res);
//        if (!"OK".equals(jsonres.getString("Code"))){
//            throw new ApiException(ErrorCodeEnum.PARAM_200012.code(),ErrorCodeEnum.PARAM_200012.msg());
//        }
//        redisService.setString(ConstantInterface.VERIFICATION_CODE_FOR_CHANGE_MOBILE + mobile, vcode, 1, TimeUnit.MINUTES);
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void updatePasswordInLogin(String account, String oldPassword, String password, String repassword) {
        UserEntity entity = new UserEntity();
        entity.setAccount(account);
        entity = userMapper.selectOne(entity);

        oldPassword = MD5Util.MD5Encode(oldPassword,"utf-8");

        if (!oldPassword.equals(entity.getPassword())){
            throw new ApiException(ErrorCodeEnum.TK1016.code(),ErrorCodeEnum.TK1016.msg());
        }
        if (!password.equals(repassword)){
            throw new ApiException(ErrorCodeEnum.TK1016.code(),ErrorCodeEnum.TK1016.msg());
        }

        password = MD5Util.MD5Encode(password, "utf-8");
        entity.setPassword(password);
        userMapper.updateByPrimaryKey(entity);

    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void updatePayPassword(String account, String password, String repassword) {

        UserEntity entity = new UserEntity();
        entity.setAccount(account);
        entity = userMapper.selectOne(entity);

        if (!password.equals(repassword)){
            throw new ApiException(ErrorCodeEnum.TK1016.code(),ErrorCodeEnum.TK1016.msg());
        }

        password = MD5Util.MD5Encode(password, "utf-8");
        entity.setPayPwd(password);
        userMapper.updateByPrimaryKey(entity);
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void checkVerificationCodeOfPayPwd(String mobile, String account, String code) {

        String vcode = redisService.getString(ConstantInterface.VERIFICATION_CODE_FOR_PAY_PASSWORD + mobile);
        if (!vcode.equals(code)){
            throw new ApiException(ErrorCodeEnum.TK1015.code(),ErrorCodeEnum.TK1015.msg());
        }

        redisService.deleteString(ConstantInterface.VERIFICATION_CODE_FOR_PAY_PASSWORD + mobile);

    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public SpecialVo aboutUs() {

        SpecialEntity entity = new SpecialEntity();
        entity.setSpKey("aboutUs");
        entity = specialMapper.selectOne(entity);

        SpecialVo specialVo = new SpecialVo();
        specialVo.setSpKey(entity.getSpKey());
        specialVo.setSpValue(entity.getSpValue());
        specialVo.setId(entity.getId());

        return specialVo;

    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public FriendsVo myTeam(String account) {
        UserEntity entity = new UserEntity();
        entity.setAccount(account);
        entity = userMapper.selectOne(entity);

        List<FriendsVo> list = new ArrayList<>();//用户的直接下级列表
        FriendsVo vo = new FriendsVo();//用户的唯一直接上级
        try {
//            //请求RD积分系统接口--我的粉丝
            Map<String, String> headers = new HashMap<String, String>();
            Map<String, String> querys = new HashMap<String, String>();
            Map<String, String> bodys = new HashMap<String, String>();
            bodys.put("username", entity.getAccount());
            HttpResponse response = HttpUtils.doPost(EOLINKERConstants.DOMAIN_URL,EOLINKERConstants.USER_FRIENDS, RequestMethod.POST.name(),headers,querys,bodys);
            String str = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(str);
//
            log.info("RD系统返回-我的粉丝：{}" + jsonObject.toJSONString());
            Integer status = jsonObject.getInteger("status");
            if (status.equals(0)){
                JSONArray array = jsonObject.getJSONArray("data");
                if (array.size()>0){
                    for (int i = 0; i < array.size(); i++){
                        FriendsVo vo1 = new FriendsVo();
                        vo1.setUserName(array.getJSONObject(i).getString("username"));
                        vo1.setCreateDate(new Timestamp(new Date().getTime()));
                        vo1.setHeadImg("http://api.shoppzsh.com/myimg/defaultImg.png");
                        list.add(vo1);
                    }
                }
            }else{
                throw new ApiException(ErrorCodeEnum.PARAM_200014.code(),String.format(ErrorCodeEnum.PARAM_200014.msg(),"我的粉丝"));
            }

            //请求RD积分系统接口--我的推荐上级
            Map<String, String> headerss = new HashMap<String, String>();
            Map<String, String> queryss = new HashMap<String, String>();
            Map<String, String> bodyss = new HashMap<String, String>();
            bodyss.put("username", entity.getAccount());
            HttpResponse responses = HttpUtils.doPost(EOLINKERConstants.DOMAIN_URL,EOLINKERConstants.USER_RECOMMEND, RequestMethod.POST.name(),headerss,queryss,bodyss);
            String strs = EntityUtils.toString(responses.getEntity());
            JSONObject jsonObjects = JSONObject.parseObject(strs);
            log.info("RD系统返回-用户推荐上级：{}" + jsonObjects.toJSONString());
            Integer statuss = jsonObjects.getInteger("status");
            if (statuss.equals(0)){
                JSONArray array = jsonObjects.getJSONArray("data");
                vo.setUserName(array.getJSONObject(0).getString("username"));
                vo.setCreateDate(new Timestamp(new Date().getTime()));
                vo.setHeadImg("http://api.shoppzsh.com/myimg/defaultImg.png");
                vo.setVos(list);
            }else{
                throw new ApiException(ErrorCodeEnum.PARAM_200014.code(),String.format(ErrorCodeEnum.PARAM_200014.msg(),"用户推荐上级"));
            }
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            throw new ApiException(ErrorCodeEnum.PARAM_200014.code(),String.format(ErrorCodeEnum.PARAM_200014.msg(),"我的粉丝/用户的上级"));
        }
        return vo;
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public PageResult<List<UserEntity>> selectByRowBounds(String account,String realName,Integer black, Integer pageSize, Integer rows,Integer grade) {

        PageResult list=new PageResult();
        Example example=new Example(UserEntity.class);
        example.setOrderByClause("user_id desc");
        Example.Criteria criteria = example.createCriteria();
        if(black!=null)
            criteria.andEqualTo("black", black);
        if(grade!=null)
            criteria.andEqualTo("grade",grade);
        if(StringUtils.isNotBlank(account))
            criteria.andLike("account","%"+account+"%");
        if(StringUtils.isNotBlank(realName))
            criteria.andLike("realName","%"+realName+"%");

        RowBounds rowBounds = RowBoundUtil.getRowBounds(rows, pageSize);
        List<UserEntity> userEntities = userMapper.selectByExampleAndRowBounds(example, rowBounds);
        list.setData(userEntities);
        int count = userMapper.selectCountByExample(example);
        list.setTotal(count);
        return list;

    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void takeBlack(Integer userId) {
        UserEntity userEntity = new UserEntity();
        userEntity.setUserId(userId);
        userEntity = userMapper.selectOne(userEntity);

        userEntity.setModifyDate(new Timestamp(new Date().getTime()));
        userEntity.setBlack(userEntity.getBlack().equals(0)? 1 : 0);//
        userMapper.updateByPrimaryKey(userEntity);

    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void setPzsh(Integer pzsh) {
        SpecialEntity specialEntity = new SpecialEntity();
        specialEntity.setSpKey("pzshPrice");
        specialEntity = specialMapper.selectOne(specialEntity);
        specialEntity.setSpValue(String.valueOf(pzsh));
        specialMapper.updateByPrimaryKey(specialEntity);

    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void setMiner(String miner) {
        SpecialEntity specialEntity = new SpecialEntity();
        specialEntity.setSpKey("minerFee");
        specialEntity = specialMapper.selectOne(specialEntity);
        specialEntity.setSpValue(miner);
        specialMapper.updateByPrimaryKey(specialEntity);
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void setAboutsUs(String about) {
        SpecialEntity specialEntity = new SpecialEntity();
        specialEntity.setSpKey("aboutUs");
        specialEntity = specialMapper.selectOne(specialEntity);
        specialEntity.setSpValue(String.valueOf(about));
        specialMapper.updateByPrimaryKey(specialEntity);
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public String getMiner() {
        SpecialEntity specialEntity = new SpecialEntity();
        specialEntity.setSpKey("minerFee");
        specialEntity = specialMapper.selectOne(specialEntity);
        return specialEntity.getSpValue();
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public String getPzsh() {
        SpecialEntity specialEntity = new SpecialEntity();
        specialEntity.setSpKey("pzshPrice");
        specialEntity = specialMapper.selectOne(specialEntity);
        return specialEntity.getSpValue();
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public String getAboutsUs() {
        SpecialEntity specialEntity = new SpecialEntity();
        specialEntity.setSpKey("aboutUs");
        specialEntity = specialMapper.selectOne(specialEntity);
        return specialEntity.getSpValue();
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public UserProfitVo getProfit(String account) {

        Long nowTime = new Date().getTime();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Long rewardDateForFind = Long.valueOf(dateFormat.format(nowTime));

        UserProfitEntity userProfitEntity = new UserProfitEntity();
        userProfitEntity.setAccount(account);
        userProfitEntity = userProfitMapper.selectOne(userProfitEntity);

        UserProfitTodayEntity userProfitTodayEntity = new UserProfitTodayEntity();
        userProfitTodayEntity.setAccount(account);
        userProfitTodayEntity.setToday(String.valueOf(rewardDateForFind));
        userProfitTodayEntity = userProfitTodayMapper.selectOne(userProfitTodayEntity);
        if(userProfitTodayEntity == null){
            userProfitTodayEntity = new UserProfitTodayEntity();
            userProfitTodayEntity.setAccount(userProfitEntity.getAccount());
            userProfitTodayEntity.setUserId(userProfitEntity.getUserId());
            userProfitTodayEntity.setPsProfit(0);
            userProfitTodayEntity.setPzshProfit(0);
            userProfitTodayEntity.setPzshReward(0);
            userProfitTodayEntity.setToday(String.valueOf(rewardDateForFind));
            userProfitTodayEntity.setCreateDate(new Timestamp(new Date().getTime()));
            userProfitTodayEntity.setModifyDate(new Timestamp(new Date().getTime()));
            userProfitTodayMapper.insert(userProfitTodayEntity);
        }
        BigDecimal oneh = new BigDecimal(100);
        BigDecimal psProfit = new BigDecimal(userProfitEntity.getPsProfit());
        BigDecimal pzshProfit = new BigDecimal(userProfitEntity.getPzshProfit());
        BigDecimal pzshReward = new BigDecimal(userProfitEntity.getPzshReward());
        BigDecimal psProfitToday = new BigDecimal(userProfitTodayEntity.getPsProfit());
        BigDecimal pzshProfitToday = new BigDecimal(userProfitTodayEntity.getPzshProfit());
        BigDecimal pzshRewardToday = new BigDecimal(userProfitTodayEntity.getPzshReward());

        UserProfitVo vo = new UserProfitVo();
        vo.setAccount(account);
        vo.setPsProfit(psProfit.divide(oneh,2, RoundingMode.HALF_UP).toString());
        vo.setPzshProfit(pzshProfit.divide(oneh,2, RoundingMode.HALF_UP).toString());
        vo.setPzshReward(pzshReward.divide(oneh,2, RoundingMode.HALF_UP).toString());
        vo.setPsProfitToday(psProfitToday.divide(oneh,2, RoundingMode.HALF_UP).toString());
        vo.setPzshProfitToday(pzshProfitToday.divide(oneh,2, RoundingMode.HALF_UP).toString());
        vo.setPzshRewardToday(pzshRewardToday.divide(oneh,2, RoundingMode.HALF_UP).toString());
        return vo;
    }

    @Override
    public String getRD2PS() {
        SpecialEntity specialEntity = new SpecialEntity();
        specialEntity.setSpKey("rd2ps");
        specialEntity = specialMapper.selectOne(specialEntity);
        return specialEntity.getSpValue();
    }

    @Override
    public void setRD2PS(Integer rd2ps) {
        SpecialEntity specialEntity = new SpecialEntity();
        specialEntity.setSpKey("rd2ps");
        specialEntity = specialMapper.selectOne(specialEntity);
        specialEntity.setSpValue(String.valueOf(rd2ps));
        specialMapper.updateByPrimaryKey(specialEntity);
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void updatePayPassword(String account, String oldPassword, String password, String repassword) {
        UserEntity entity = new UserEntity();
        entity.setAccount(account);
        entity = userMapper.selectOne(entity);

        oldPassword = MD5Util.MD5Encode(oldPassword,"utf-8");

        if (!oldPassword.equals(entity.getPayPwd())){
            throw new ApiException(ErrorCodeEnum.TK1016.code(),ErrorCodeEnum.TK1016.msg());
        }
        if (!password.equals(repassword)){
            throw new ApiException(ErrorCodeEnum.TK1016.code(),ErrorCodeEnum.TK1016.msg());
        }

        password = MD5Util.MD5Encode(password, "utf-8");
        entity.setPayPwd(password);
        userMapper.updateByPrimaryKey(entity);
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void updateMobile(String account, String mobile, String code) {

        if (!redisService.hasKey(ConstantInterface.VERIFICATION_CODE_FOR_CHANGE_MOBILE + mobile)){
            throw new ApiException(ErrorCodeEnum.TK1015.code(),ErrorCodeEnum.TK1015.msg());
        }
        if (!code.equals(redisService.getString(ConstantInterface.VERIFICATION_CODE_FOR_CHANGE_MOBILE + mobile))){
            throw new ApiException(ErrorCodeEnum.TK1015.code(),ErrorCodeEnum.TK1015.msg());
        }
        UserEntity entity = new UserEntity();
        entity.setAccount(account);
        entity = userMapper.selectOne(entity);
        entity.setMobile(mobile);
        userMapper.updateByPrimaryKey(entity);
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void sendVerificationCodeForPayPwd(String mobile, String account) {

        String vcode = String.valueOf((int)(Math.random()*(9999-1000+1)+1000));

        redisService.setString(ConstantInterface.VERIFICATION_CODE_FOR_PAY_PASSWORD + mobile, vcode, 1, TimeUnit.MINUTES);
        SendSms.send(vcode,mobile);
//        String res = SendSms.send(vcode,mobile);
//        JSONObject jsonres = JSONObject.parseObject(res);
//        if (!"OK".equals(jsonres.getString("Code"))){
//            throw new ApiException(ErrorCodeEnum.PARAM_200012.code(),ErrorCodeEnum.PARAM_200012.msg());
//        }
//        redisService.setString(ConstantInterface.VERIFICATION_CODE_FOR_PAY_PASSWORD + mobile, vcode, 1, TimeUnit.MINUTES);
    }


    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void registry_initUser(String account, String mobile,String pass, String visitAccount){

        UserEntity aaa = new UserEntity();
        aaa.setAccount("starUser42");
        aaa = userMapper.selectOne(aaa);
        if (aaa != null){
            throw new ApiException(ErrorCodeEnum.SW51.code(),ErrorCodeEnum.SW51.msg());
        }

        UserEntity visitAcc = new UserEntity();
        visitAcc.setAccount(visitAccount);
        visitAcc = userMapper.selectOne(visitAcc);
        if (visitAcc == null){
            throw new ApiException(ErrorCodeEnum.PARAM_200017.code(),ErrorCodeEnum.PARAM_200017.msg());
        }

        pass = MD5Util.MD5Encode(pass,"utf-8");

        //用户注册
        UserEntity entity = new UserEntity();
        entity.setAccount(account);
        entity.setPassword(pass);
        entity.setMobile(mobile);
        entity.setVisitAccount(visitAccount);
        entity.setGrade(5);
        entity.setBlack(0);
        entity.setStatus(0);
        entity.setHead("http://api.shoppzsh.com/myimg/defaultImg.png");
        entity.setIdCard("--");
        entity.setRealName("--");
        entity.setBankCard("--");
        entity.setCreateDate(new Timestamp(new Date().getTime()));
        entity.setModifyDate(new Timestamp(new Date().getTime()));
        userMapper.insert(entity);

        log.info("添加用户后的userId = {}", entity.getUserId()==null?"null":entity.getUserId());
        Integer superid = 0;

        //保存推荐人的好友
        UserEntity visitor = new UserEntity();
        visitor.setAccount(visitAccount);
        visitor = userMapper.selectOne(visitor);
        superid = visitor.getUserId();
        FriendsEntity friendsEntity = new FriendsEntity();
        friendsEntity.setFriends_id(entity.getUserId());
        friendsEntity.setFriendsName(entity.getAccount());
        friendsEntity.setMobile(entity.getMobile());
        friendsEntity.setUserId(visitor.getUserId());
        friendsEntity.setUserName(visitor.getAccount());
        friendsMapper.insert(friendsEntity);

        //初始化用户消费累计记录
        UserSpendEntity userSpendEntity = new UserSpendEntity();
        userSpendEntity.setSpendMoney(0);
        userSpendEntity.setSpendMoneyGoods(0);
        userSpendEntity.setSpendMoneyGrade(0);
        userSpendEntity.setUserId(entity.getUserId());
        spendMoneyMapper.insert(userSpendEntity);

        //初始化用户钱包，0
        UserPackEntity userPackEntity = new UserPackEntity();
        userPackEntity.setUserId(entity.getUserId());
        userPackEntity.setFreeIntegral(0);
        userPackEntity.setRewardIntegral(0);
        userPackEntity.setEUSDT(0);
        userPackEntity.setPZSH(0);
        userPackEntity.setRdIntegral(0);
        userPackEntity.setUnuseIntegral(0);
        userPackMapper.insert(userPackEntity);

        //初始化注册用户的团队成员
        GradeConditionEntity gradeConditionEntity = new GradeConditionEntity();
        gradeConditionEntity.setFriends(0);
        gradeConditionEntity.setReConsumption(0);
        gradeConditionEntity.setTeam(0);
        gradeConditionEntity.setUserId(entity.getUserId());
        gradeConditionEntity.setUserName(entity.getAccount());
        gradeConditionEntity.setSuperName(visitAccount);
        gradeConditionEntity.setSuperId(superid);
        gradeConditionMapper.insert(gradeConditionEntity);

        //请求RD积分系统接口--创建用户
        Map<String, String> headers = new HashMap<String, String>();
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("username", entity.getAccount());
        bodys.put("name", "");
        bodys.put("nickname", "");
        bodys.put("p_username", entity.getVisitAccount());
        bodys.put("mobile", entity.getMobile());
        try {
            HttpResponse response = HttpUtils.doPost(EOLINKERConstants.DOMAIN_URL, EOLINKERConstants.USER_ADD, RequestMethod.POST.name(),headers,querys,bodys);
            String str = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(str);//.getJSONObject("data")
            Integer status = jsonObject.getInteger("status");
            log.info("RD系统返回-创建用户：{}",jsonObject.toJSONString());
            if (!status.equals(0)){
                throw new ApiException(ErrorCodeEnum.PARAM_200014.code(),String.format(ErrorCodeEnum.PARAM_200014.msg(),"创建用户"));
            }
        } catch (Exception e) {
            throw new ApiException(ErrorCodeEnum.PARAM_200014.code(),String.format(ErrorCodeEnum.PARAM_200014.msg(),"创建用户"));
        }


        redisService.deleteString(ConstantInterface.VERIFICATION_CODE_FOR_REGISTER + mobile);
    }
    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void addUserPS(String account, Integer iii) {
        UserEntity userEntity = new UserEntity();
        userEntity.setAccount(account);
        userEntity = userMapper.selectOne(userEntity);
        if (userEntity== null){
            throw new ApiException(ErrorCodeEnum.SW50.code(),ErrorCodeEnum.SW50.msg());
        }
        if (iii <= 0){
            throw new ApiException(ErrorCodeEnum.PARAM_200020.code(),ErrorCodeEnum.PARAM_200020.msg());
        }

        UserPackEntity userPackEntity = new UserPackEntity();
        userPackEntity.setUserId(userEntity.getUserId());
        userPackEntity = userPackMapper.selectOne(userPackEntity);

        userPackEntity.setFreeIntegral(userPackEntity.getFreeIntegral() + iii);
        userPackMapper.updateByPrimaryKey(userPackEntity);

        //添加明细记录 用户发放PS进账
        TransactionEntity in = new TransactionEntity();
        in.setNumb(iii);
        in.setRemark("发放PS");
        in.setTType(14);
        in.setCreateDate(new Timestamp(new Date().getTime()));
        in.setModifyDate(new Timestamp(new Date().getTime()));
        in.setRecordType(3);
        in.setInoutType(1);
        in.setUserId(userEntity.getUserId());
        in.setAccount(userEntity.getAccount());
        transactionssMapper.insert(in);

    }
    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public int getUserCount() {
        return userMapper.selectAll().size();
    }
    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void toGrade(String account, Integer grade) {
        UserEntity entity = new UserEntity();
        entity.setAccount(account);
        entity = userMapper.selectOne(entity);
        entity.setGrade(grade-1);
        userMapper.updateByPrimaryKey(entity);
    }
    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void initUserProfitToday() {

        Long nowTime2 = new Date().getTime() + 24 * 60 * 60 * 1000L;
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyyMMdd");
        Long rewardDateForFind2 = Long.valueOf(dateFormat2.format(nowTime2));

        List<UserEntity> userEntities = userMapper.selectAll();
        for (UserEntity userEntity : userEntities){
            //初始化明日的收益
            UserProfitTodayEntity userProfitTodayEntity2 = new UserProfitTodayEntity();
            userProfitTodayEntity2.setToday(String.valueOf(rewardDateForFind2));
            userProfitTodayEntity2.setUserId(userEntity.getUserId());
            userProfitTodayEntity2 = userProfitTodayMapper.selectOne(userProfitTodayEntity2);
            if (userProfitTodayEntity2 == null){
                userProfitTodayEntity2 = new UserProfitTodayEntity();
                userProfitTodayEntity2.setAccount(userEntity.getAccount());
                userProfitTodayEntity2.setUserId(userEntity.getUserId());
                userProfitTodayEntity2.setPsProfit(0);
                userProfitTodayEntity2.setPzshProfit(0);
                userProfitTodayEntity2.setPzshReward(0);
                userProfitTodayEntity2.setToday(String.valueOf(rewardDateForFind2));
                userProfitTodayEntity2.setCreateDate(new Timestamp(new Date().getTime()));
                userProfitTodayEntity2.setModifyDate(new Timestamp(new Date().getTime()));
                userProfitTodayMapper.insert(userProfitTodayEntity2);
            }
        }
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public String getLevelRule() {

        SpecialEntity specialEntity = new SpecialEntity();
        specialEntity.setSpKey("levelRule");
        specialEntity = specialMapper.selectOne(specialEntity);
        return specialEntity.getSpValue();
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public void setLevelRule(String levelRule) {
        SpecialEntity specialEntity = new SpecialEntity();
        specialEntity.setSpKey("levelRule");
        specialEntity = specialMapper.selectOne(specialEntity);
        specialEntity.setSpValue(levelRule);
        specialMapper.updateByPrimaryKey(specialEntity);
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public JSONObject getRdRecord(String account,String page) {
        //请求RD积分系统接口--创建用户
        Map<String, String> headers = new HashMap<String, String>();
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("username", account);
        bodys.put("page", page);
        try {
            HttpResponse response = HttpUtils.doPost(EOLINKERConstants.DOMAIN_URL, EOLINKERConstants.REWARD_LISTS, RequestMethod.POST.name(),headers,querys,bodys);
            String str = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(str);

            Integer status = jsonObject.getInteger("status");
            log.info("RD系统返回-钱包明细：{}",jsonObject.toJSONString());
            if (!status.equals(0)){
                throw new ApiException(ErrorCodeEnum.PARAM_200014.code(),String.format(ErrorCodeEnum.PARAM_200014.msg(),"钱包明细"));
            }
            return jsonObject;
        } catch (Exception e) {
            throw new ApiException(ErrorCodeEnum.PARAM_200014.code(),String.format(ErrorCodeEnum.PARAM_200014.msg(),"钱包明细"));
        }
    }

    @Transactional(propagation=Propagation.REQUIRED)
    @Override
    public RTVo getRecommedAndTeam(String account) {
        //判断团队人数--数据来源RD系统
        Integer group = 0 ;
        //判断直推人数是否符合购买条件
        Integer child = 0 ;
        try {
            Map<String, String> headers = new HashMap<String, String>();
            Map<String, String> querys = new HashMap<String, String>();
            Map<String, String> bodys = new HashMap<String, String>();
            bodys.put("username", account);
            HttpResponse response = HttpUtils.doPost(EOLINKERConstants.DOMAIN_URL,EOLINKERConstants.USER_NUMBER, RequestMethod.POST.name(),headers,querys,bodys);
            String str = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(str);
//            log.info("RD系统返回-我的会员人数统计：{}",jsonObject.toJSONString());
            Integer status = jsonObject.getInteger("status");
            if (!status.equals(0)){
                throw new ApiException(ErrorCodeEnum.PARAM_200014.code(),String.format(ErrorCodeEnum.PARAM_200014.msg(),"我的会员人数统计"));
            }
            group = jsonObject.getJSONObject("data").getInteger("group");
            child = jsonObject.getJSONObject("data").getInteger("child");
            RTVo rtVo = new RTVo();
            rtVo.setRecommend(child);
            rtVo.setTeam(group);
            return rtVo;
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            throw new ApiException(ErrorCodeEnum.PARAM_200014.code(),String.format(ErrorCodeEnum.PARAM_200014.msg(),"我的会员人数统计"));
        }
    }

    @Override
    public void whiteUser(Integer userId) {

        WhiteUserEntity whiteUserEntity = new WhiteUserEntity();
        whiteUserEntity.setUserId(userId);
        whiteUserEntity = whiteUserMapper.selectOne(whiteUserEntity);
        if (whiteUserEntity == null){
            whiteUserEntity = new WhiteUserEntity();
            whiteUserEntity.setUserId(userId);
            whiteUserEntity.setCreateDate(new Timestamp(new Date().getTime()));
            whiteUserEntity.setModifyDate(new Timestamp(new Date().getTime()));
            whiteUserMapper.insert(whiteUserEntity);
        }

        UserEntity userEntity = new UserEntity();
        userEntity.setUserId(userId);
        userEntity = userMapper.selectOne(userEntity);
        userEntity.setBlack(0);
        userEntity.setModifyDate(new Timestamp(new Date().getTime()));
        userMapper.updateByPrimaryKey(userEntity);

    }

    @Override
    public String getRewardPs() {
        SpecialEntity specialEntity = new SpecialEntity();
        specialEntity.setSpKey("rewardPs");
        specialEntity = specialMapper.selectOne(specialEntity);
        return specialEntity.getSpValue();
    }

    @Override
    public void setRewardPs(String iii) {
        SpecialEntity specialEntity = new SpecialEntity();
        specialEntity.setSpKey("rewardPs");
        specialEntity = specialMapper.selectOne(specialEntity);
        specialEntity.setSpValue(iii);
        specialMapper.updateByPrimaryKey(specialEntity);
    }


    public void registry_initUser1(){

//        Map<String,String> map1 = new HashMap();
//        map1.put("account","pingzhi1");map1.put("mobile","");map1.put("pass","123aaa");map1.put("visitAccount","pingzhi0");
//        registry_initUser1(map1);

//        Map<String,String> map2 = new HashMap();
//        map2.put("account","pingzhi2");map2.put("mobile","");map2.put("pass","pzsh123");map2.put("visitAccount","pingzhi1");
//        registry_initUser1(map2);

//        Map<String,String> map3 = new HashMap();
//        map3.put("account","pingzhi3");map3.put("mobile","");map3.put("pass","pzsh123");map3.put("visitAccount","pingzhi2");
//        registry_initUser1(map3);
//
//        Map<String,String> map4 = new HashMap();
//        map4.put("account","pingzhi4");map4.put("mobile","");map4.put("pass","pzsh123");map4.put("visitAccount","pingzhi3");
//        registry_initUser1(map4);
//
//        Map<String,String> map5 = new HashMap();
//        map5.put("account","pingzhi5");map5.put("mobile","");map5.put("pass","pzsh123");map5.put("visitAccount","pingzhi4");
//        registry_initUser1(map5);
//


//        Map<String,String> map7 = new HashMap();
//        map7.put("account","pingzhi7");map7.put("mobile","");map7.put("pass","pzsh123");map7.put("visitAccount","pingzhi4");
//        registry_initUser1(map7);

//        Map<String,String> map6 = new HashMap();
//        map6.put("account","pingzhi6");map6.put("mobile","");map6.put("pass","pzsh123");map6.put("visitAccount","pingzhi4");
//        registry_initUser1(map6);

//        Map<String,String> map8 = new HashMap();
//        map8.put("account","weiyun1");map8.put("mobile","");map8.put("pass","pzsh123");map8.put("visitAccount","pingzhi5");
//        registry_initUser1(map8);
//
//        Map<String,String> map9 = new HashMap();
//        map9.put("account","weiyun2");map9.put("mobile","");map9.put("pass","pzsh123");map9.put("visitAccount","pingzhi5");
//        registry_initUser1(map9);
//
//        Map<String,String> map10 = new HashMap();
//        map10.put("account","weiyun3");map10.put("mobile","");map10.put("pass","pzsh123");map10.put("visitAccount","pingzhi5");
//        registry_initUser1(map10);
//
//        Map<String,String> map11 = new HashMap();
//        map11.put("account","weiyun4");map11.put("mobile","");map11.put("pass","pzsh123");map11.put("visitAccount","pingzhi6");
//        registry_initUser1(map11);
//
//        Map<String,String> map12 = new HashMap();
//        map12.put("account","weiyun5");map12.put("mobile","");map12.put("pass","pzsh123");map12.put("visitAccount","pingzhi6");
//        registry_initUser1(map12);

//        Map<String,String> map13 = new HashMap();
//        map13.put("account","weiyun6");map13.put("mobile","");map13.put("pass","pzsh123");map13.put("visitAccount","pingzhi6");
//        registry_initUser1(map13);
//
//        Map<String,String> map15 = new HashMap();
//        map15.put("account","weiyun8");map15.put("mobile","");map15.put("pass","pzsh123");map15.put("visitAccount","pingzhi7");
//        registry_initUser1(map15);
//
//        Map<String,String> map14 = new HashMap();
//        map14.put("account","weiyun7");map14.put("mobile","");map14.put("pass","pzsh123");map14.put("visitAccount","pingzhi7");
//        registry_initUser1(map14);
//
//        Map<String,String> map16 = new HashMap();
//        map16.put("account","weiyun9");map16.put("mobile","");map16.put("pass","pzsh123");map16.put("visitAccount","pingzhi7");
//        registry_initUser1(map16);

    }

    public void registry_initUser1(Map<String,String> map){

        String account = map.get("account");
        String mobile = map.get("mobile");
        String pass=map.get("pass");
        String visitAccount=map.get("visitAccount");
        UserEntity entity = new UserEntity();
//        entity.setAccount(account);
//        entity = userMapper.selectOne(entity);
//        if (entity != null){
//            throw new ApiException(ErrorCodeEnum.SW51.code(),ErrorCodeEnum.SW51.msg());
//        }

//        UserEntity visitAcc = new UserEntity();
//        visitAcc.setAccount(visitAccount);
//        visitAcc = userMapper.selectOne(visitAcc);
//        if (visitAcc == null){
//            throw new ApiException(ErrorCodeEnum.PARAM_200017.code(),ErrorCodeEnum.PARAM_200017.msg());
//        }
//        if (visitAcc.getGrade()==-1){
//            throw new ApiException(ErrorCodeEnum.PARAM_200025.code(),ErrorCodeEnum.PARAM_200025.msg());
//        }

//        UserEntity entitymm = new UserEntity();
//        entitymm.setMobile(mobile);
//        entitymm = userMapper.selectOne(entitymm);
//        if (entitymm != null){
//            throw new ApiException(ErrorCodeEnum.SW53.code(),ErrorCodeEnum.SW53.msg());
//        }

        pass = MD5Util.MD5Encode(pass,"utf-8");
        //用户注册
        entity = new UserEntity();
        entity.setAccount(account);
        entity.setPassword(pass);
        entity.setMobile("");
        entity.setVisitAccount(visitAccount);
        entity.setGrade(5);
        entity.setBlack(0);
        entity.setStatus(1);
        entity.setHead("http://api.shoppzsh.com/myimg/defaultImg.png");
        entity.setIdCard("--");
        entity.setRealName("--");
        entity.setBankCard("--");
        entity.setCreateDate(new Timestamp(new Date().getTime()));
        entity.setModifyDate(new Timestamp(new Date().getTime()));
        userMapper.insert(entity);

        System.out.println("添加用户后的userId = {}"+ entity.getUserId()==null?"null":entity.getUserId());
        Integer superid = 0;

        //保存推荐人的好友
        UserEntity visitor = new UserEntity();
        visitor.setAccount(visitAccount);
        visitor = userMapper.selectOne(visitor);
        superid = visitor.getUserId();
        FriendsEntity friendsEntity = new FriendsEntity();
        friendsEntity.setFriends_id(entity.getUserId());
        friendsEntity.setFriendsName(entity.getAccount());
        friendsEntity.setMobile(entity.getMobile());
        friendsEntity.setUserId(visitor.getUserId());
        friendsEntity.setUserName(visitor.getAccount());
        friendsMapper.insert(friendsEntity);

        //初始化用户消费累计记录
        UserSpendEntity userSpendEntity = new UserSpendEntity();
        userSpendEntity.setSpendMoney(0);
        userSpendEntity.setSpendMoneyGoods(0);
        userSpendEntity.setSpendMoneyGrade(0);
        userSpendEntity.setUserId(entity.getUserId());
        spendMoneyMapper.insert(userSpendEntity);

        //初始化用户钱包，0
        UserPackEntity userPackEntity = new UserPackEntity();
        userPackEntity.setUserId(entity.getUserId());
        userPackEntity.setFreeIntegral(0);
        userPackEntity.setRewardIntegral(0);
        userPackEntity.setEUSDT(0);
        userPackEntity.setPZSH(0);
        userPackEntity.setRdIntegral(0);
        userPackEntity.setUnuseIntegral(0);
        userPackMapper.insert(userPackEntity);

        //初始化注册用户的团队成员
        GradeConditionEntity gradeConditionEntity = new GradeConditionEntity();
        gradeConditionEntity.setFriends(0);
        gradeConditionEntity.setReConsumption(0);
        gradeConditionEntity.setTeam(0);
        gradeConditionEntity.setUserId(entity.getUserId());
        gradeConditionEntity.setUserName(entity.getAccount());
        gradeConditionEntity.setSuperName(visitAccount);
        gradeConditionEntity.setSuperId(superid);
        gradeConditionMapper.insert(gradeConditionEntity);

        //**累计用户总数
        CensusEntity censusEntity = censusMapper.selectAll().get(0);
        censusEntity.setCountUser(censusEntity.getCountUser()+1);
        censusMapper.updateByPrimaryKey(censusEntity);

        //初始化用户总收益记录
        UserProfitEntity userProfitEntity = new UserProfitEntity();
        userProfitEntity.setAccount(entity.getAccount());
        userProfitEntity.setUserId(entity.getUserId());
        userProfitEntity.setPsProfit(0);
        userProfitEntity.setPzshProfit(0);
        userProfitEntity.setPzshReward(0);
        userProfitMapper.insert(userProfitEntity);

        //初始化用户今日收益记录
        Long nowTime = new Date().getTime();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Long rewardDateForFind = Long.valueOf(dateFormat.format(nowTime));
        UserProfitTodayEntity userProfitTodayEntity = new UserProfitTodayEntity();
        userProfitTodayEntity.setToday(String.valueOf(rewardDateForFind));
        userProfitTodayEntity.setUserId(entity.getUserId());
        userProfitTodayEntity = userProfitTodayMapper.selectOne(userProfitTodayEntity);
        if (userProfitTodayEntity == null){
            userProfitTodayEntity = new UserProfitTodayEntity();
            userProfitTodayEntity.setAccount(entity.getAccount());
            userProfitTodayEntity.setUserId(entity.getUserId());
            userProfitTodayEntity.setPsProfit(0);
            userProfitTodayEntity.setPzshProfit(0);
            userProfitTodayEntity.setPzshReward(0);
            userProfitTodayEntity.setToday(String.valueOf(rewardDateForFind));
            userProfitTodayEntity.setCreateDate(new Timestamp(new Date().getTime()));
            userProfitTodayEntity.setModifyDate(new Timestamp(new Date().getTime()));
            userProfitTodayMapper.insert(userProfitTodayEntity);
        }

        //初始化明日的收益记录
        Long nowTime2 = new Date().getTime() + 24 * 60 * 60 * 1000L;
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyyMMdd");
        Long rewardDateForFind2 = Long.valueOf(dateFormat2.format(nowTime2));
        UserProfitTodayEntity userProfitTodayEntity2 = new UserProfitTodayEntity();
        userProfitTodayEntity2.setToday(String.valueOf(rewardDateForFind2));
        userProfitTodayEntity2.setUserId(entity.getUserId());
        userProfitTodayEntity2 = userProfitTodayMapper.selectOne(userProfitTodayEntity2);
        if (userProfitTodayEntity2 == null){
            userProfitTodayEntity2 = new UserProfitTodayEntity();
            userProfitTodayEntity2.setAccount(entity.getAccount());
            userProfitTodayEntity2.setUserId(entity.getUserId());
            userProfitTodayEntity2.setPsProfit(0);
            userProfitTodayEntity2.setPzshProfit(0);
            userProfitTodayEntity2.setPzshReward(0);
            userProfitTodayEntity2.setToday(String.valueOf(rewardDateForFind2));
            userProfitTodayEntity2.setCreateDate(new Timestamp(new Date().getTime()));
            userProfitTodayEntity2.setModifyDate(new Timestamp(new Date().getTime()));
            userProfitTodayMapper.insert(userProfitTodayEntity2);
        }

        //请求RD积分系统接口--创建用户
        Map<String, String> headers = new HashMap<String, String>();
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("username", entity.getAccount());
        bodys.put("name", "");
        bodys.put("nickname", "");
        bodys.put("p_username", entity.getVisitAccount());
        bodys.put("mobile", entity.getMobile());
        try {
            HttpResponse response = HttpUtils.doPost(EOLINKERConstants.DOMAIN_URL, EOLINKERConstants.USER_ADD, RequestMethod.POST.name(),headers,querys,bodys);
            String str = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(str);//.getJSONObject("data")
            Integer status = jsonObject.getInteger("status");
            System.out.println("RD系统返回-创建用户：{}"+jsonObject.toJSONString());
            if (!status.equals(0)){
                throw new ApiException(ErrorCodeEnum.PARAM_200014.code(),String.format(ErrorCodeEnum.PARAM_200014.msg(),"创建用户"));
            }
        } catch (Exception e) {
            throw new ApiException(ErrorCodeEnum.PARAM_200014.code(),String.format(ErrorCodeEnum.PARAM_200014.msg(),"创建用户"));
        }

    }
}
